﻿/// <reference path="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\MicrosoftAjax.js" />
/// <reference path="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\SP.debug.js" />
/// <reference path="../libs/jquery-1.8.2-vsdoc.js" />

var SCA = SCA || {};
SCA.DAL = SCA.DAL || {};

SCA.DAL.SP = function (absoluteUrl) {

    this.absoluteUrl = absoluteUrl;
    this.rootWeb;

    this.Init = function(onSuccessCallback, onFailCallback) {
        this.rootWeb = new SCA.DAL.Web(this.absoluteUrl);
        this.rootWeb.Load(onSuccessCallback, onFailCallback);
    }
}

SCA.DAL.SP.CallWebService = function (webServiceUrl, soapBody, callbackSuccess, callbackFail) {
        var soapMessage = '<?xml version="1.0" encoding="utf-8"?>' +
                             '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">' +
                               '<soap:Body>' +
                                  soapBody +
                               '</soap:Body>' +
                             '</soap:Envelope>';

        

        jQuery.ajax({
            type: "POST",
            url: webServiceUrl,
            data: soapMessage,
            contentType: "text/xml; charset=utf-8",
            dataType: "xml",
            success: callbackSuccess,
            error: callbackFail
        });
}


///returns in the 'callbackSuccess' the url of the web site in the given 'url'
SCA.DAL.SP.GetWebUrlFromUrl = function (absoluteUrl, url, callbackSuccess, callbackFail) {
    var webServiceUrl = absoluteUrl + "/_vti_bin/" + "webs.asmx";
    var soapBody = '<WebUrlFromPageUrl xmlns="http://schemas.microsoft.com/sharepoint/soap/">' +
                        '<pageUrl>'+ url +'</pageUrl>' +
                    '</WebUrlFromPageUrl>';

    var webServiceCallbackSuccess = function (data) {
        var webUrl = data.getElementsByTagName("WebUrlFromPageUrlResult")[0].text;
        callbackSuccess(webUrl);
    }

    var webServiceCallbackFail = function (data){
        console.log("SCA.DAL.SP.GetWebUrlFromUrl:" + data.statusText + " - " + data.responseText);
        callbackFail();
    }

    SCA.DAL.SP.CallWebService(webServiceUrl, soapBody, webServiceCallbackSuccess, webServiceCallbackFail);
}





SCA.DAL.Web = function(absoluteUrl, title, serverUrl){
    this.absoluteUrl = absoluteUrl;
    this.title = title;
    this.id;
    this.serverUrl = serverUrl;

    var countLoadAsyncCalls = 0;

    this.websCollection = new Array();
    this.listsCollection = new Array();

    this.onSuccessCallback;
    this.onFailCallback;

    this.Load = function(onSuccessCallback, onFailCallback)
    {
        this.onSuccessCallback = onSuccessCallback;
        this.onFailCallback = onFailCallback;

        countLoadAsyncCalls = 3;
        this.LoadWeb();
        this.LoadSubWebs();
        this.LoadLists();
    }

    this.LoadWeb = function () {
        var soapBody = '<GetWeb xmlns="http://schemas.microsoft.com/sharepoint/soap/">' +
                            '<webUrl>' + this.absoluteUrl + '</webUrl>' +
                        '</GetWeb>';

        var webServiceUrl = this.absoluteUrl + "/_vti_bin/" + "webs.asmx";
        SCA.DAL.SP.CallWebService(webServiceUrl, soapBody, Function.createDelegate(this, this.onLoadWebSucceeded), Function.createDelegate(this, this.onLoadFailed));
    }

    this.LoadSubWebs = function ()
    {
        var webServiceUrl = this.absoluteUrl + "/_vti_bin/" + "webs.asmx";
        SCA.DAL.SP.CallWebService(webServiceUrl, '<GetWebCollection xmlns="http://schemas.microsoft.com/sharepoint/soap/"/>', Function.createDelegate(this, this.onLoadSubWebsSucceeded), Function.createDelegate(this, this.onLoadFailed));
    }

    this.LoadLists = function()
    {
        var webServiceUrl = this.absoluteUrl + "/_vti_bin/" + "lists.asmx";
        SCA.DAL.SP.CallWebService(webServiceUrl, '<GetListCollection xmlns="http://schemas.microsoft.com/sharepoint/soap/" />', Function.createDelegate(this, this.onLoadListsSucceeded), Function.createDelegate(this, this.onLoadFailed));
    }

    this.onLoadWebSucceeded = function(data)
    {
        var web = data.getElementsByTagName("Web")[0];
        this.title = web.getAttribute("Title");
        this.id = web.getAttribute("Id");

        this.onLoadSucceeded();
    }

    this.onLoadSubWebsSucceeded = function (data)
    {
        var subWebs = data.getElementsByTagName("Web");
        for(var i = 0 ;i < subWebs.length; i++)
        {
            var title = subWebs[i].getAttribute("Title");
            var absoluteUrl = subWebs[i].getAttribute("Url");
            var web = new SCA.DAL.Web(absoluteUrl, title);
            this.websCollection.push(web);
        }
        
        this.onLoadSucceeded();
    }

    this.onLoadListsSucceeded = function (data) {
        var lists = data.getElementsByTagName("List");
        for (var i = 0 ; i < lists.length; i++) {
            if (lists[i].getAttribute("Hidden").toString().toLowerCase() === "true") {
                continue;
            }
            var title = lists[i].getAttribute("Title");
            var id = lists[i].getAttribute("ID");
            if (this.serverUrl == null) {
                var serverRelativeUrlOfParentWeb = lists[i].getAttribute("WebFullUrl");
                this.serverUrl = this.absoluteUrl.replace(serverRelativeUrlOfParentWeb, "");
            }
            var list = new SCA.DAL.List(title, this.absoluteUrl, null, id, this.serverUrl);
            this.listsCollection.push(list);
        }

        this.onLoadSucceeded();
    }

    this.onLoadSucceeded = function()
    {
       countLoadAsyncCalls--;
        if(countLoadAsyncCalls == 0)
        {
            this.onSuccessCallback();
        }
    }

    this.onLoadFailed = function (data) {
        console.log("SCA.DAL.Web:" + data.statusText + " - " + data.responseText);
        this.onFailCallback();
    }
    
}





SCA.DAL.List = function (title, parentWebAbsoluteUrl, serverRelativeUrl, id, serverUrl) {
    this.title = title;
    this.parentWebAbsoluteUrl = parentWebAbsoluteUrl;
    this.serverRelativeUrl = serverRelativeUrl;
    this.id = id;
    this.serverUrl = serverUrl;
    this.absoluteUrl = ((serverUrl != null) && (serverRelativeUrl != null)) ? serverUrl + serverRelativeUrl : null;
    
    this.rootFolder = new SCA.DAL.Folder("RootFolder", null, this); 
    this.contentTypeCollection = new Array();
   
    this.onSuccessCallback;
    this.onFailCallback;

    var countLoadAsyncCalls = -1;

    this.Load = function(onSuccessCallback, onFailCallback)
    {
        this.onSuccessCallback = onSuccessCallback;
        this.onFailCallback = onFailCallback;

        countLoadAsyncCalls = 2;
        this.LoadListDetails();
        this.LoadTheContentTypes();
    }

    this.LoadTheContentTypes = function () { //do not rename to LoadContentTypes
        var soapBody = '<GetListContentTypes xmlns="http://schemas.microsoft.com/sharepoint/soap/">' +
                            '<listName>' + this.title + '</listName>' +
                            '<contentTypeId />' +
                       '</GetListContentTypes>';

        var webServiceUrl = this.parentWebAbsoluteUrl + "/_vti_bin/" + "lists.asmx";
        SCA.DAL.SP.CallWebService(webServiceUrl, soapBody, Function.createDelegate(this, this.onLoadContentTypesSucceeded), Function.createDelegate(this, this.onLoadFailed));
    }

    this.LoadListDetails = function (){
        var soapBody =  '<GetList xmlns="http://schemas.microsoft.com/sharepoint/soap/">'+
                            '<listName>'+ this.title +'</listName>"'+
                        '</GetList>';

        var webServiceUrl = this.parentWebAbsoluteUrl + "/_vti_bin/" + "lists.asmx";
        SCA.DAL.SP.CallWebService(webServiceUrl, soapBody, Function.createDelegate(this, this.onLoadListDetailsSucceeded), Function.createDelegate(this, this.onLoadFailed));
    }

    this.onLoadContentTypesSucceeded = function (data) {
        //debugger;
        var contentTypes = data.getElementsByTagName("ContentType");
        for (var i = 0 ; i < contentTypes.length; i++) {
            var title = contentTypes[i].getAttribute("Name");
            var id = contentTypes[i].getAttribute("ID");
            var contentType = new SCA.DAL.ContentType(title, id);
            this.contentTypeCollection.push(contentType);
        }
        this.onLoadSucceeded();
    }

    this.onLoadListDetailsSucceeded = function (data)
    {
        var list = data.getElementsByTagName("List")[0];
        var rootFolderUrl = list.getAttribute("RootFolder");
        this.serverRelativeUrl = rootFolderUrl;
        this.absoluteUrl = this.serverUrl + this.serverRelativeUrl;
        this.rootFolder = new SCA.DAL.Folder("RootFolder", rootFolderUrl, this);
        this.onLoadSucceeded();
    }

    this.onLoadSucceeded = function () {
        countLoadAsyncCalls--;
        if (countLoadAsyncCalls == 0) {
            this.onSuccessCallback();
        }
    }

    this.onLoadFailed = function (data) {
        console.log("SCA.DAL.List:" + data.statusText + " - " + data.responseText);
        this.onFailCallback();
    }
}





SCA.DAL.ContentType = function(title, id){
    this.title = title;
    this.id = id;
}





SCA.DAL.Folder = function (title, serverRelativeUrl, parent, id, childCount) {
    this.serverRelativeUrl = serverRelativeUrl;
    this.title = title;
    this.id = id;
    this.parent = parent;
    this.isRootFolder = parent instanceof SCA.DAL.List;
    this.serverUrl = (parent != null) ? parent.serverUrl : null;

    this.childCount = childCount;
    this.subFolderAndItemCollection = new Array();
    this.absoluteUrl = ((this.serverUrl != null) && (serverRelativeUrl != null)) ? this.serverUrl + serverRelativeUrl : null;

    this.parentList = (this.isRootFolder) ? this.parent : ( (this.parent == null) ? null : this.parent.parentList );
    
    var countLoadAsyncCalls = 0;

    this.Load = function(onSuccessCallback, onFailCallback){
        this.onSuccessCallback = onSuccessCallback;
        this.onFailCallback = onFailCallback;

        countLoadAsyncCalls = 1;
        this.LoadImmediateSubfoldersAndItems();
    }

    this.LoadImmediateSubfoldersAndItems = function (){
        var query = '<Query xmlns="" />';
        var queryOptionsCAML = '<QueryOptions xmlns="" />';
        if (!this.isRootFolder)
        {
            //debugger;
            query = '<Query xmlns="">' +
                        '<Where>' +
                            '<Eq>' +
                                '<FieldRef Name="FileDirRef" />' +
                                    '<Value Type="Text">' + this.serverRelativeUrl + '</Value>' +
                            '</Eq>' +
                        '</Where>' +
                    '</Query>';
            queryOptionsCAML = '<QueryOptions xmlns=""><Folder>' + this.title + '</Folder></QueryOptions>';
        }

        var soapBody = '<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">' +
                            '<listName>' + this.parentList.title + '</listName>' +
                            '<query>' + query + '</query>'+
                            '<viewFields><ViewFields xmlns=""><FieldRef Name="Title" /><FieldRef Name="ItemChildCount" /><FieldRef Name="ContentType" /></ViewFields></viewFields>' +
                            '<queryOptions>' + queryOptionsCAML + '</queryOptions>' +
                        '</GetListItems>';

        var webServiceUrl = this.parentList.parentWebAbsoluteUrl + "/_vti_bin/" + "lists.asmx";
        SCA.DAL.SP.CallWebService(webServiceUrl, soapBody, Function.createDelegate(this, this.onLoadImmediateSubfoldersAndItemsSucceeded), Function.createDelegate(this, this.onLoadFailed));
    }


    this.onLoadImmediateSubfoldersAndItemsSucceeded = function (data) {
        var items = data.getElementsByTagName("z:row");
        for (var i = 0; i < items.length; i++) {
            var contentType = items[i].getAttribute("ows_ContentType");
            var title = items[i].getAttribute("ows_Title");
            if (title == null) {
                title = Clean(items[i].getAttribute("ows_FileLeafRef"));
            }
            var id = Clean(items[i].getAttribute("ows_UniqueId"));
            var serverRelativeUrl = Clean(items[i].getAttribute("ows_FileRef"));
            if (serverRelativeUrl.charAt(0) != '/') {
                serverRelativeUrl = '/' + serverRelativeUrl;
            }
            if (contentType.toLowerCase() == "folder"){
                var childCount = Clean(items[i].getAttribute("ows_ItemChildCount"));
                var folder = new SCA.DAL.Folder(title, serverRelativeUrl, this, id, childCount);
                this.subFolderAndItemCollection.push(folder);
            }
            else{
                var item = new SCA.DAL.Item(title, serverRelativeUrl, id);
                this.subFolderAndItemCollection.push(item);
            }
        }
  
        this.onLoadSucceeded();
    }

    function Clean(string)
    {
        var index = string.indexOf(";#");
        return (index == -1) ?  string : string.substr(index + 2);
    }


    this.onLoadSucceeded = function () {
        countLoadAsyncCalls--;
        if (countLoadAsyncCalls == 0) {
            this.onSuccessCallback();
        }
    }

    this.onLoadFailed = function (data) {
        console.log("SCA.DAL.Folder:" + data.statusText + " - " + data.responseText);
        this.onFailCallback();
    }

}





SCA.DAL.Item = function (title, serverRelativeUrl, id) {
    this.title = title;
    this.serverRelativeUrl = serverRelativeUrl;
    this.id = id;
}